from flask import render_template, g, redirect, request, jsonify, current_app

from info import constants
from info import db
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET
from info.utils.image_storage import storage
from info.models import Category, News


@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        # 加载新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 移除最新的分类
        category_dict_li.pop(0)

        return render_template('news/user_news_release.html', data={'categories': category_dict_li})

    # 1、获取要提交的参数
    # 标题
    title = request.form.get('title')
    # 新闻来源
    source = '个人发布'
    # 摘要
    digest = request.form.get('digest')
    # 新闻内容
    content = request.form.get('content')
    # 索引图片
    index_image = request.files.get('index_image')
    # 分类id
    category_id = request.form.get('category_id')

    # 2、校验参数
    # 判断参数是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(erron=RET.PARAMERR, errmsg='获取请求参数错误')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.PARAMERR, errmsg='新闻分类参数有误')

    # 3、取到图片，上传到七牛云
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.PARAMERR, errmsg='图片参数错误')

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表审核中，0代表审核通过，-1代表审核不通过
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(erron=RET.DBERR, errmsg='数据保存失败')

    return jsonify(erron=RET.OK, errmsg='OK')


@profile_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 1、获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    # 2、校验参数
    if not all([old_password, new_password]):
        return jsonify(erron=RET.PARAMERR, errmsg='获取参数失败')

    # 3、判断就密码是否正确
    user = g.user
    if not user.check_password(old_password):
        return jsonify(erron=RET.PWDERR, errmsg='旧密码错误')

    # 4、设置新密码
    user.password = new_password
    return jsonify(erron=RET.OK, errmsg='OK')


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    # 不同的请求参数代表做不同的事
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data=data)

    # post代表修改头像
    # 1、取到上传的图片
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.PARAMERR, errmsg='获取图片参数失败')
    # 2、上传图片
    try:
        # 使用自己封装的storage进行图片上传
        key = storage(avatar)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.THIRDERR, errmsg='上传图片失败')

    # 3、保存图片url
    user.avatar_url = key
    return jsonify(erron=RET.OK, errmsg='OK', data={'avatar_url': constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    # 不同的请求参数代表做不同的事
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data=data)

    # 修改用户数据
    # 1、取到传入的参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 2、校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(erron=RET.PARAMERR, errmsg='请求参数错误')

    if gender not in ['WOMAN', 'MAN']:
        return jsonify(erron=RET.PARAMERR, errmsg='性别参数错误')

    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(erron=RET.OK, errmsg='OK')


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    # 如果用户未登录，重定向到首页
    if not user:
        return redirect('/')
    data = {'user': user.to_dict()}
    return render_template('news/user.html', data=data)
